package com.autohelper.app;

import android.content.Context;
import android.content.Intent;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.content.pm.PackageManager;
import android.util.Log;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class PermissionUtils {
    private static final String TAG = "PermissionUtils";
    public static final int PERMISSION_REQUEST_CODE = 1000;

    /**
     * 检查所有必需权限
     */
    public static void checkAndRequestPermissions(Context context) {
        // 检查无障碍服务
        if (!isAccessibilityServiceEnabled(context)) {
            showAccessibilitySettingDialog(context);
        }

        // 检查悬浮窗权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(context)) {
            showOverlayPermissionDialog(context);
        }

        // 检查存储权限（Android 10以下）
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            checkStoragePermissions(context);
        }
    }

    /**
     * 检查无障碍服务是否启用
     */
    public static boolean isAccessibilityServiceEnabled(Context context) {
        int accessibilityEnabled = 0;
        try {
            accessibilityEnabled = Settings.Secure.getInt(context.getContentResolver(),
                    Settings.Secure.ACCESSIBILITY_ENABLED);
        } catch (Settings.SettingNotFoundException e) {
            Log.e(TAG, "获取无障碍服务状态失败: " + e.getMessage());
        }

        if (accessibilityEnabled == 1) {
            String service = context.getPackageName() + "/" + AutoAccessibilityService.class.getCanonicalName();
            String enabledServices = Settings.Secure.getString(
                    context.getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            return enabledServices != null && enabledServices.contains(service);
        }
        return false;
    }

    /**
     * 检查悬浮窗权限
     */
    public static boolean checkOverlayPermission(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return Settings.canDrawOverlays(context);
        }
        return true;
    }

    /**
     * 检查存储权限
     */
    public static void checkStoragePermissions(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] permissions = {
                    android.Manifest.permission.READ_EXTERNAL_STORAGE,
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE
            };

            for (String permission : permissions) {
                if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    if (context instanceof android.app.Activity) {
                        ActivityCompat.requestPermissions(
                                (android.app.Activity) context,
                                permissions,
                                PERMISSION_REQUEST_CODE);
                    }
                    break;
                }
            }
        }
    }

    /**
     * 显示无障碍服务设置对话框
     */
    public static void showAccessibilitySettingDialog(Context context) {
        new AlertDialog.Builder(context)
                .setTitle("需要无障碍服务权限")
                .setMessage("请在设置中启用无障碍服务")
                .setPositiveButton("去设置", (dialog, which) -> {
                    Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                })
                .setCancelable(false)
                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 显示悬浮窗权限设置对话框
     */
    public static void showOverlayPermissionDialog(Context context) {
        new AlertDialog.Builder(context)
                .setTitle("需要悬浮窗权限")
                .setMessage("请授予悬浮窗权限以显示操作步骤")
                .setPositiveButton("去设置", (dialog, which) -> {
                    try {
                        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                        intent.setData(Uri.parse("package:" + context.getPackageName()));
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intent);
                    } catch (Exception e) {
                        Log.e(TAG, "打开悬浮窗设置失败: " + e.getMessage());
                        Toast.makeText(context, "打开设置失败，请手动授予悬浮窗权限",
                                Toast.LENGTH_LONG).show();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 检查截屏权限是否已授予
     */
    public static boolean isScreenCaptureEnabled(Context context) {
        return ServiceHolder.INSTANCE.getScreenCaptureManager().isScreenCaptureEnabled();
    }

    /**
     * 显示截屏权限设置对话框
     */
    public static void showScreenCaptureDialog(Context context) {
        new AlertDialog.Builder(context)
                .setTitle("需要截屏权限")
                .setMessage("请授予截屏权限以实现自动化功能")
                .setPositiveButton("去设置", (dialog, which) -> {
                    if (context instanceof MainActivity) {
                        MediaProjectionManager mediaProjectionManager = (MediaProjectionManager) context.getSystemService(Context.MEDIA_PROJECTION_SERVICE);
                        ((MainActivity) context).startActivityForResult(
                                mediaProjectionManager.createScreenCaptureIntent(),
                                MainActivity.REQUEST_CODE_CAPTURE_SCREEN);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }
}